[Coding003] LeetCode 18

4Sum

Ben 2023/07/26

More coding records

Get the knowledge flowing and circulating! :)

目录

题目:4Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have *exactly* one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Example 2:

Example 3:

Constraints:

Follow-up: Can you come up with an algorithm that is less than O(n2)time complexity?

解题

解题思路

延续3sum的思路,用双指针可以做!

这次提供两套实现代码:

  1. 利用HashSet本身的集合特性来去重!

  2. 利用基本的去重代码来实现!

 

重要测试样例

代码1

 

代码2

Line22的绘图解释!

解释一下那个j是如何变化的!

复杂度分析

第1个for循环,耗时O(n)

第2个for循环,耗时O(n)

里面还有一个while循环,耗时O(n)

所以,嵌套起来,时间复杂度应该是:O(n3)

知识点积累 (Java)

  1. HashSet自带去重功能

  2. Arrays.asList()操作,可以省略了3Sum中间的繁琐步骤了!

  3. Java的整型(int)会溢出